package com.vast.metrix.viewer.bustraffic.controllers;

import org.eclipse.core.runtime.ListenerList;
import org.eclipse.swt.widgets.Display;
import org.jfree.data.time.TimeSeries;
import com.vast.ui.component.state.Sequence;

public class AutoRefreshFire  implements Runnable {
	private Display        display;
	private TimeSeries[]   triggerTimeSeriesArray;
	private Sequence       sequence;
	private final  ListenerList listenerList;
	private boolean        isChartUpdate = true;
	private int            refreshRate_ms;
	
	public AutoRefreshFire(Sequence sequence, Display display, TimeSeries[] timeSeriesArray, int refreshRate_ms) {
		this.listenerList           = new ListenerList();
		this.sequence               = sequence;
		this.display                = display;
		this.triggerTimeSeriesArray = timeSeriesArray;
		this.refreshRate_ms         = refreshRate_ms;
	}

	public void addListener(IRefreshListener listener){
		listenerList.add(listener);
	}
	
	public void removeListener(IRefreshListener listener){
		listenerList.remove(listener);
	}
	
	public synchronized void run() {
		// TODO Auto-generated method stub
		Object[] listeners = listenerList.getListeners();
		for (Object listener : listeners) {
			((IRefreshListener) listener).refresh();
		}
		
		if (!this.display.isDisposed() && this.sequence.isReceiveConnection() && isChartUpdate()) {
			this.display.asyncExec(new Runnable() {
				public void run() {
					for (int i = 0; i < triggerTimeSeriesArray.length; i++) {
						triggerTimeSeriesArray[i].fireSeriesChanged();
					}
				}
			});
		}
		
		if (!display.isDisposed() && this.sequence.isReceiveConnection()) {
			try {
				wait(refreshRate_ms);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			display.asyncExec(this);
		}
	}
	
	public synchronized void setUpdateChart(boolean isChartUpdate){
		this.isChartUpdate = isChartUpdate;
	}
	
	public synchronized boolean isChartUpdate() {
		return this.isChartUpdate;
	}
}

